@extends('admin.home.main')

@section('body')

<style type="text/css">
	.box{width:100%; display:none;}
	.box.cur{display:block;}
	.top{width:100%; overflow:hidden; border-bottom:1px solid #ccc; padding:5px 0; margin-bottom:10px;}
	.top-left{width:70%; float:left;}
	.top-right{width:110px; height:85px; border:1px solid #ccc; padding:4px; display:block; float:left;}
	.top img{width:100px; height:75px;}
	.content{width:100%; overflow:hidden; border-top:1px solid #ccc; padding-top:10px; margin-top:10px;}

	.fieldset {border:1px solid #afe14c; margin:10px 0; padding:20px 10px;}
	.fieldset span.legend { position: relative; background-color: #FFF; padding: 3px; top: -30px; font: 700 14px Arial, Helvetica, sans-serif; color: #73b304;}

	.flash { width: 375px; margin: 19px 0; border-color: #D9E4FF;
 -moz-border-radius-topleft : 5px; -webkit-border-top-left-radius : 5px; -moz-border-radius-topright : 5px; -webkit-border-top-right-radius : 5px; -moz-border-radius-bottomleft : 5px; -webkit-border-bottom-left-radius : 5px; -moz-border-radius-bottomright : 5px; -webkit-border-bottom-right-radius : 5px;}
	input[disabled]{ border: 1px solid #ccc } /* FF 2 Fix */
	#btnSubmit { margin: 0 0 0 155px ; }
	.progressWrapper {width: 357px; overflow: hidden;}
	.progressContainer {margin: 5px;padding: 4px;border: solid 1px #E8E8E8;background-color: #F7F7F7;overflow: hidden;}
	/* Message */
	.message {margin: 1em 0;padding: 10px 20px;border: solid 1px #FFDD99;background-color: #FFFFCC;overflow: hidden;}
	/* Error */
	.red {border: solid 1px #B50000;background-color: #FFEBEB;}
	/* Current */
	.green {border: solid 1px #DDF0DD;background-color: #EBFFEB;}
	/* Complete */
	.blue {border: solid 1px #CEE2F2;background-color: #F0F5FF;}
	.progressName {font-size: 8pt;font-weight: 700;color: #555;width: 323px;height: 14px;text-align: left;white-space: nowrap;overflow: hidden;}
	.progressBarInProgress,.progressBarComplete,.progressBarError {font-size: 0;width: 0%;height: 2px;background-color: blue;margin-top: 2px;}
	.progressBarComplete {width: 100%;background-color: green;visibility: hidden;}
	.progressBarError {width: 100%;background-color: red;visibility: hidden;}
	.progressBarStatus {margin-top: 2px;width: 337px;font-size: 7pt;font-family: Arial;text-align: left;white-space: nowrap;}
	a.progressCancel {font-size: 0;display: block;height: 14px;width: 14px;background-image: url({{asset('img/cancelbutton.gif')}});background-repeat: no-repeat;background-position: -14px 0px;float: right;}
	a.progressCancel:hover {background-position: 0px 0px;}
	.swfupload {vertical-align: top;}

</style>
<link href="{{asset('webuploader/webuploader.css')}}" type="text/css" rel="stylesheet">
<script type="text/javascript" src="{{asset('webuploader/webuploader.js')}}"></script>
<section id="main-content">
	<section class="wrapper">
		<h3>课程分类添加</h3>
		<!-- BASIC FORM ELELEMNTS -->
		<div class="row mt">
		  	<div class="col-lg-12">
				<div class="form-panel">
				  <form class="form-horizontal style-form" action="/admin/course/update" method="post" id="art_form" enctype="multipart/form-data">
				  	<input type="hidden" id="_token" name="_token" value="{{csrf_token()}}">
				  	<input type="hidden" name="courseid" id="courseid" value="{{$courseid}}">
				  	<input type="file" class="material_file" name="material_file" style="display:none;">
				  	<input type="hidden" name="course" id="course" value="course">
				  	<div class="top">
				  		<div class="top-left">
							<p style="color:red; font-size:16px;">备注：课程题图1 图片尺寸：165.5x165.5像素(px) 图片格式：*.png,*.jpg</p>
							<p style="color:red; font-size:16px;">备注：课程题图2 图片尺寸：343x150像素(px) 图片格式：*.png,*.jpg</p>
				  			<div class="form-group">
							  <label class="col-sm-2 col-sm-2 control-label">课程分类名称</label>
							  <div class="col-sm-10">
								<select class="form-control" id="tmid" name="tmid" style="width:200px; float:left;">
				               		<option value="0">请选择</option>
				               		@foreach($ctlist as $ctm=>$cst)
				               			<option value="{{$cst->id}}" @if($courseinfo->tmid == $cst->id)selected="selected"@endif>{{$cst->type_name}}</option>
				               		@endforeach
				                </select>
								  <select class="form-control" id="tid" name="tid" style="width:150px;float:left; margin-left:5px;" disabled="disabled">
									  <option value="0">请选择</option>
								  </select>
							  </div>
							</div>

							<div class="form-group">
							  <label class="col-sm-2 col-sm-2 control-label">课程名称</label>
							  <div class="col-sm-10">
								<input type="text" style="width:400px;" class="form-control" id="name" name="name" placeholder="请输入课程名称" size="50" value="{{$courseinfo->name}}">
							  </div>
							</div>
				  		</div>
				  		<!-- <a href='javascript:;' file_id = "1" class="top-right add_img" onclick="uploadPhoto()"> -->
						@if($courseinfo->thumb)
							<a href='javascript:;' file_id = "1" class="top-right add_img">
								<img id="title_pic" src="{{$courseinfo->thumb}}" alt="">
							</a>
						@else
							<a href='javascript:;' file_id = "1" class="top-right add_img" style="text-align:center;">
								<img id="title_pic" src="" style="display:none;" alt="">
							</a>
						@endif
						<input type="hidden" id="t_imgsrc" name="imgsrc" value="{{$courseinfo->thumb}}">

						@if($courseinfo->thumb2)
							<a href='javascript:;' file_id = "3" class="top-right add_img" style="width:170px;
							height:120px; margin-left:10px;">
								<img id="title_pic2" src="{{$courseinfo->thumb2}}" alt="" style="width:160px;
								height:110px;">
							</a>
						@else
							<a href='javascript:;' file_id = "3" class="top-right add_img"
							   style="width:170px; height:120px; text-align:center; margin-left:10px;">
								<img id="title_pic2" src="" alt="" style="display:none;" style="width:160px;
								height:110px">
							</a>
						@endif
						<input type="hidden" id="t_imgsrc2" name="imgsrc2" value="{{$courseinfo->thumb2}}">
				  	</div>
				  	

					
					<button type="button" id="btn" class="btn btn-warning" style="margin-bottom:10px;">点此展开</button><span style="margin-left:10px;color:red;">修改具体内容请点击该按钮</span><br>
					<div class="box">
						<div class="form-group">
						  <label class="col-sm-2 col-sm-2 control-label">课程简介</label>
						  <div class="col-sm-10">
							<input type="text" style="width:400px;" class="form-control" id="desc" name="desc" placeholder="请输入课程简介" size="50" value="{{$courseinfo->desc}}">
						  </div>
						</div>
						<div class="form-group">
						  <label class="col-sm-2 col-sm-2 control-label">课程价格</label>
						  <div class="col-sm-10">
							<input type="text" style="width:400px;" class="form-control" id="price" name="price" placeholder="请输入课程价格" size="50" value="{{$courseinfo->price}}">
						  </div>
						</div>

						<div class="form-group">
						  <label class="col-sm-2 col-sm-2 control-label">课程集数</label>
						  <div class="col-sm-10">
							<input type="text" style="width:400px;" class="form-control" id="videonum" name="videonum" placeholder="请输入课程集数" size="50" value="{{$courseinfo->video_num}}">
						  </div>
						</div>

						<div class="form-group">
						  <label class="col-sm-2 col-sm-2 control-label">课程标签</label>
						  <div class="col-sm-10">
						  	@foreach($taglist as $atm=>$ast)
								<input type="checkbox" class="tag" name="tag" value="{{$ast->id}}" @if(in_array($ast->id,$courseinfo->ctlist)) checked="checked" @endif> {{$ast->tag_name}}&nbsp;&nbsp;
							@endforeach
						  </div>
						</div>

						<div class="form-group">
						  <label class="col-sm-2 col-sm-2 control-label">课程总数量</label>
						  <div class="col-sm-10">
							<input type="text" style="width:400px;" class="form-control" id="coursenum" name="coursenum" placeholder="请输入课程总数量" size="50" value="{{$courseinfo->curriculum_num}}">
						  </div>
						</div>

						<div class="form-group">
						  <label class="col-sm-2 col-sm-2 control-label">是否免费</label>
						  <div class="col-sm-10">
							<input type="radio" class="isfree" name="isfree" value="1" @if($courseinfo->isfree == 1) checked="checked" @endif> 不免费&nbsp;&nbsp;
							<input type="radio" class="isfree" name="isfree" value="0" @if($courseinfo->isfree == 0) checked="checked" @endif> 免费&nbsp;&nbsp;
							<input type="radio" class="isfree" name="isfree" value="2" @if($courseinfo->isfree == 2) checked="checked" @endif> 部分免费&nbsp;&nbsp;
						  </div>
						</div>
						
						<div class="form-group">
						  <label class="col-sm-2 col-sm-2 control-label">单集购买</label>
						  <div class="col-sm-10">
							<input type="radio" class="isbuy" name="isbuy" value="1" @if($courseinfo->is_buy_one == 1) checked="checked" @endif> 支持&nbsp;&nbsp;
							<input type="radio" class="isbuy" name="isbuy" value="0" @if($courseinfo->is_buy_one == 0) checked="checked" @endif> 不支持&nbsp;&nbsp;
						  </div>
						</div>
					</div>

					<div class="content">
						<div class="form-group">
							<label class="col-sm-2 col-sm-2 control-label">课程权重</label>
							<div class="col-sm-10">
								<input type="text" style="width:400px;" class="form-control" id="weight" name="weight"
									   placeholder="请输入权重" size="50" value="{{$courseinfo->weight}}">
								<p>备注：权重数字越大课程排名越靠前</p>
							</div>
						</div>
						<div class="form-group">
							<label class="col-sm-2 col-sm-2 control-label">课程详情</label>
							<div class="col-sm-10">
								<a class="btn btn-theme02 add_img" href="javascript:;" file_id = "2">选择图片</a>
								<!-- <a class="btn btn-theme02 add_img" file_id = "2" href="javascript:;" onclick="uploadPhoto()">选择>图片</a> -->

								<div class="fileupload-new thumbnail" style="width: 200px; margin-top:10px;">
									<img id="content" src="@if($courseinfo->content) {{$courseinfo->content}} @else http://www.placehold.it/200x150/EFEFEF/AAAAAA&text=no+image @endif" alt="">
								</div>
								<input type="hidden" id="c_imgsrc" name="c_imgsrc" value="{{$courseinfo->content}}">
							</div>
						</div>

		                <div class="form-group">
		                  <label class="col-sm-2 col-sm-2 control-label">上传视频</label>
		                  <div class="col-sm-10">
		                  	<!--<div>
		                  		<span id="spanButtonPlaceHolder"></span>
								<input id="btnCancel" type="button" value="取消上传" onclick="swfu.cancelQueue();"  class="btn btn-default" style="height:29px;" disabled="disabled" />
		                  	</div>
		                  	<div class="fieldset flash" id="fsUploadProgress">
								<span class="legend">Upload Queue</span>
							</div>
		                  	<div id="divStatus">0 Files Uploaded</div>-->

							  <div id="uploader" class="wu-example">
								  <!--用来存放文件信息-->
								  <div id="thelist" class="uploader-list"></div>
								  <div class="btns">
									  <div id="picker">选择文件</div>
									  <button type="button" id="ctlBtn" class="btn btn-default">开始上传</button>
								  </div>
								  <div>
									  <progress id="progress" style="display:none;" max=1 value=0></progress>
									  <span id="per" style="display:none;">0%</span>
								  </div>
							  </div>
		                  	<div class="">
		                  		@foreach($coursevideolist as $cvm=>$cst)
		                  			<a class="btn btn-default" href="{{$cst->video_link}}">第{{$cvm+1}}集</a>
		                  		@endforeach
		                  	</div>
		                  	<div id="video_link"></div>
						  </div>
		                </div>
					</div>
					<!-- <input type="text" name="video" id="video" value=""> -->
					<button type="button" id="save" class="btn btn-success">提交</button>
					<button type="reset" class="btn btn-primary">重置</button>
				  </form>
				</div>
		  	</div>
		  	<!-- col-lg-12-->
		</div>
	</section>
</section>

{{--<script type="text/javascript" src="{{asset('swfupload/swfupload.js')}}"></script>--}}
{{--<script type="text/javascript" src="{{asset('js/swfupload.queue.js')}}"></script>--}}
{{--<script type="text/javascript" src="{{asset('js/fileprogress.js')}}"></script>--}}
{{--<script type="text/javascript" src="{{asset('js/handlers.js')}}"></script>--}}
<script type="text/javascript">
	$(function(){
		function get_suffix(filename) {
			pos = filename.lastIndexOf('.')
			suffix = ''
			if (pos != -1) {
				suffix = filename.substring(pos)
			}
			return suffix;
		}

		function random_string(len) {
			len = len || 32;
			var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
			var maxPos = chars.length;
			var pwd = '';
			for (i = 0; i < len; i++) {
				pwd += chars.charAt(Math.floor(Math.random() * maxPos));
			}
			return pwd;
		}

		var uploader = WebUploader.create({
			auto:false,

			// swf文件路径
			swf: '{{asset('webuploader/Uploader.swf')}}',

			// 文件接收服务端。
			server: 'http://boom-dog.oss-cn-zhangjiakou.aliyuncs.com',

			// 选择文件的按钮。可选。
			// 内部根据当前运行是创建，可能是input元素，也可能是flash.
			pick: '#picker',

			// 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
			resize: false
		});

		uploader.on( 'fileQueued', function( file ) {
			$('#thelist').append( '<div id="' + file.id + '" class="item">' +
					'<h4 class="info">' + file.name + '</h4>' +
					'<p class="state">等待上传...</p>' +
					'<input type="hidden" class="video_uri ">'+
					'</div>' );
		});

		// 文件上传过程中创建进度条实时显示。
		uploader.on( 'uploadProgress', function( file, percentage ) {
			var $li = $( '#'+file.id ),
					$percent = $li.find('.progress .progress-bar');

			// 避免重复创建
			if ( !$percent.length ) {
				$percent = $('<div class="progress progress-striped active">' +
						'<div class="progress-bar" role="progressbar" style="width: 0%">' +
						'</div>' +
						'</div>').appendTo( $li ).find('.progress-bar');
			}

			$li.find('p.state').text('上传中');

			$percent.css( 'width', percentage * 100 + '%' );
		});

		uploader.on('uploadBeforeSend',function(obj,data,headers){
			var ext = get_suffix(data.name);
			var filename = random_string()+ext;
			$.ajax({
				url:'/admin/common/getsign/{{$courseid}}',
				type:'get',
				dataType:'json',
				async:false,
				success:function(res){
					// console.log(res);
					res = eval(res);
					$.extend(data,{
						'key':res.dir+filename,
						'policy':res.policy,
						'OSSAccessKeyId':res.accessid,
						'success_action_status':'200',
						'callback':res.callback,
						'signature':res.signature
					})
				}
			});
		});

		$('#ctlBtn').click(function(){
			uploader.upload();
		})

		uploader.on( 'uploadSuccess', function( file,msg) {
			$( '#'+file.id ).find('p.state').text('已上传');
			var hosturl = 'http://boom-dog.oss-cn-zhangjiakou.aliyuncs.com/';
			$( '#'+file.id).find('input.video_uri').val(hosturl+msg.file_name);
			console.log(msg);
		});

		//var swfu;

		/*window.onload = function() {
			var settings = {
				flash_url : "{{asset('swfupload/swfupload.swf')}}",
				upload_url: "/admin/course/upload",
				post_params: {'_token':'{{csrf_token()}}','file':'course','courseid':{{$courseinfo->id}}},
				file_size_limit : "80 MB",
				file_types : "*.*",
				file_types_description : "All Files",
				file_upload_limit : 100,
				file_queue_limit : 0,
				custom_settings : {
					progressTarget : "fsUploadProgress",
					cancelButtonId : "btnCancel"
				},
				debug: false,

				// Button settings
				button_image_url: "{{asset('img/TestImageNoText_65x29.png')}}",
				button_width: "65",
				button_height: "29",
				button_placeholder_id: "spanButtonPlaceHolder",
				button_text: '上传视频',
				button_text_style: ".theFont {}",
				button_text_left_padding: 6,
				button_text_top_padding: 6,
				
				// The event handler functions are defined in handlers.js
				file_queued_handler : fileQueued,
				file_queue_error_handler : fileQueueError,
				file_dialog_complete_handler : fileDialogComplete,
				upload_start_handler : uploadStart,
				upload_progress_handler : uploadProgress,
				upload_error_handler : uploadError,
				upload_success_handler : uploadsuccessful,
				upload_complete_handler : uploadComplete,
				queue_complete_handler : queueComplete	// Queue plugin event
			};

			swfu = new SWFUpload(settings);
	    };*/

		var main_tid = $('#tmid').val();
		var tid = {{$courseinfo->tid}};

		$.ajax({
			url:'/admin/common/getcoursetypelist/'+main_tid,
			type:'get',
			dataType:'json',
			success:function(data){
				if(data.code == 200){
					var _data = data.list.data;
					var _html = '<option value="0">请选择</option>';
					for(var i=0; i < _data.length; i++) {
						if (tid == _data[i].id){
							_html += '<option value="' + _data[i].id + '" selected="selected">' + _data[i].type_name + '</option>';
						}else{
							_html += '<option value="' + _data[i].id + '">' + _data[i].type_name + '</option>';
						}
					}
					$('#tid').html(_html);
					$('#tid').removeAttr('disabled');
				}
			}
		});

	    /*function uploadsuccessful(file,serverData){
	    	try {
                var progress = new FileProgress(file, this.customSettings.progressTarget);

                progress.setComplete();
                progress.setStatus("上传成功");
                progress.toggleCancel(false);
            } catch (ex) {
                this.debug(ex);
            }
            var url=serverData;
            var _url = JSON.parse(url);
			var serverurl = 'https://boom-dog.oss-cn-zhangjiakou.aliyuncs.com/'+_url.source_src;
            if(_url.code ==200){
            	$('#video_link').append('<input type="text" name="video_src" class="video_src form-control" disabled="disabled" style="width:400px;" value="'+serverurl+'">');
            }

	    }*/

		var thisId;
	    $('.w-e-icon-image').click(function(){
			thisId = $(this).attr('file_id');
			$('.material_file').click();
			return false;
		})

		$('.add_img').click(function(){
			thisId = $(this).attr('file_id');
			$('.material_file').click();
		})

		$('.material_file').change(function(){
			upload(thisId);
		})

		function upload(thisId){
			if($('.material_file').val() == ''){
	    		alert('请选择图片');
	    		return false;
	    	}
			

	    	var formData = new FormData($('#art_form')[0]);
	    	$.ajax({
	    		url:'/admin/common/upload',
				// url:'/admin/material/uploads',
	    		type:'post',
	    		data:formData,
	    		dataType:'json',
	    		contentType: false,
	            processData: false,
	            success:function(data){
	            	if(data.code == 200){
	            		var _imgsrc = 'https://boom-dog.oss-cn-zhangjiakou.aliyuncs.com/'+data.imgurl;
	            		if(thisId == 1){
	            			$('#title_pic').attr('src',_imgsrc);
	            			$('#t_imgsrc').val(_imgsrc);
	            			$('#title_pic').removeAttr('style');
	            		}else if(thisId == 3){
	            			$('#title_pic2').attr('src',_imgsrc);
	            			$('#t_imgsrc2').val(_imgsrc);
	            			$('#title_pic2').removeAttr('style');
						}else{
	            			$('#content').attr('src',_imgsrc);
	            			$('#c_imgsrc').val(_imgsrc);
	            		}
	            		
	            		alert('上传成功');
	            	}else{
	            		alert('上传失败');
	            	}
	            	return false;
	            }
	    	})
		}

        $("#btn").click(function(){
            $(".box").toggleClass("cur")
        })

		var free = '';
		$('.isfree').each(function(){
			if($(this).is(':checked')){
				free = $(this).val();
			}

			if(free == 0){
				$('.isbuy').attr('disabled','disabled');
			}else{
				$('.isbuy').removeAttr('disabled');
			}
		})


		$('.isfree').click(function(){
			free = $(this).val();
			if(free == 0){
				$('.isbuy').attr('disabled','disabled');
			}else{
				$('.isbuy').removeAttr('disabled');
			}
		})

        $('#save').click(function(){
			var _token = $('#_token').val(),
				courseid = $('#courseid').val(),
				name = $('#name').val(),
				tid = $('#tid').val(),
				desc = $('#desc').val(),
				price = $('#price').val(),
				videonum = $('#videonum').val(),
				coursenum = $('#coursenum').val(),
				title_pic1 = $('#t_imgsrc').val(),
				title_pic2 = $('#t_imgsrc2').val(),
				content = $('#c_imgsrc').val(),
				tag = [],
				isfree = '',
				video_src = [],
				weight = $('#weight').val(),
				isbuy = '';
			$('.video_uri').each(function(){
				if($(this).val() != ''){
					video_src.push($(this).val());
				}
			})

			var _videosrc = video_src.join(',');
			
			$('.tag').each(function(){
				if($(this).is(':checked')){
					tag.push($(this).val());
				}
			})

			var _tag = tag.join(',');

			$('.isbuy').each(function(){
				if($(this).is(':checked')){
					isbuy = $(this).val();
				}
			})

			$('.isfree').each(function(){
				if($(this).is(':checked')){
					isfree = $(this).val();
				}
			})

			if(!tid){
				alert('请选择课程分类');
				return false;
			}

			if(!name){
				alert('请输入课程名称');
				return false;
			}

			if(!desc){
				alert('请输入课程简介');
				return false;
			}

			if(!price){
				alert('请输入课程价格');
				return false;
			}

			if(!videonum){
				alert('请输入课程集数');
				return false;
			}

			if(!_tag){
				alert('请选择课程标签');
				return false;
			}

			if(!isfree){
				alert('请选择是否免费');
				return false;
			}else{
				isbuy = 0;
			}

			if(isfree > 0 && isbuy < 0){
				alert('请选择是否支持单集购买');
				return false;
			}

			if(!weight){
				alert('请输入课程权重');
				return false;
			}

			$.ajax({
				url:'/admin/course/update',
				type:'post',
				data:{'_token':_token,'id':courseid,'name':name,'title_pic':title_pic1,'title_pic2':title_pic2,
					'content':content,'tmid':main_tid,'tid':tid,'desc':desc,'price':price,'tag':_tag,'isbuy':isbuy,
					'videonum':videonum,'coursenum':coursenum,'is_free':isfree,'video_src':_videosrc,'weight':weight},
				dataType:'json',
				success:function(msg){
					if(msg.code == 200){
						alert('编辑成功');
						location.href="/admin/course/list/";
					}else{
						alert('编辑失败');
						return false;
						location.reload();
					}
				}
			})
		})
    })

	
</script>
@endsection